package com.zhxq.member.service.impl;

import com.zhxq.ai.repository.ChatHistoryRepository;
import com.zhxq.ai.repository.FileRepository;
import com.zhxq.common.utils.UserThreadLocal;
import com.zhxq.member.service.IMemberInterviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@Service
@Slf4j
public class MemberInterviewServiceImpl implements IMemberInterviewService {

    @jakarta.annotation.Resource
    private ChatHistoryRepository mongoChatHistoryRepository;

    @jakarta.annotation.Resource
    private ChatClient interviewChatClient;

    @Autowired
    private FileRepository fileRepository;

    /**
     * 面试会话
     * @param prompt
     * @param chatId
     * @return
     * @throws InterruptedException
     */
    @Override
    public Flux<String> chat(String prompt, String chatId, String position) throws InterruptedException {
        mongoChatHistoryRepository.save("interview", chatId);
        Long userId = UserThreadLocal.getUserId();
        Resource file = fileRepository.getFile(chatId);
        log.info("file: {}", file.getFilename());
        return interviewChatClient.prompt()
                .user(prompt + "（客户ID：" + userId + "面试职位：" + position + ")")
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .advisors(a -> a.param(QuestionAnswerAdvisor.FILTER_EXPRESSION, "file_name == '"+file.getFilename()+"'"))
                .stream()
                .content();
    }
}
